package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {

	public void setUpServer(int port){
		try {
			ServerSocket ss = new ServerSocket(port);
			while(true){
				Socket client = ss.accept();
				System.out.println("Incoming Address" + client.getRemoteSocketAddress());
				processChat(client);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void processChat(Socket client){
		try {
			InputStream ins = client.getInputStream();
			OutputStream os = client.getOutputStream();
			String bytesN = "welcome to chatroom\r\n";
			byte[] bytes = bytesN.getBytes();
			os.write(bytes);
			os.flush();
			String inputStr = readString(ins);
			while(!"bye".equals(inputStr)){
				bytesN = "server receive:" + inputStr +"\r\n";
				os.write(bytesN.getBytes());
				os.flush();
				System.out.println("current string = "+ inputStr);
				inputStr = readString(ins);
			}
			System.out.println("User has pressed BYE");
			String bye = "see you\r\n";
			byte[] byes = bye.getBytes();
			os.write(byes);
			os.flush();
			
			os.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public String readString(InputStream istream) throws IOException{
		StringBuilder sb = new StringBuilder();
		int in = 0;
		char c =0;
		while(in!=13){
			in = istream.read();
			c = (char)in;
			sb.append(c);
		}
		return sb.toString().trim();
	}
	
	public static void main(String[] args) {
		ChatServer server = new ChatServer();
		server.setUpServer(9090);

	}

}
